<!-- 使用示例 -->
<template>
  <div class="page-wrapper">

    <el-row :gutter="24" class="page-container">
      <!-- 时间统计图表区域 -->
      <el-col :md="12" class="chart-col">
        <el-card class="stat-card" shadow="hover">
          <div class="card-header">
            <div class="header-left">
              <h3 class="section-title">
                <el-icon><PieChart /></el-icon>
                时间统计
              </h3>
              <div class="stats-tags">
                <el-tag type="success" class="total-time">
                  总时长: {{ formatMinutesToTime(totalSales) }}
                </el-tag>
                <el-tag :type="calculateDailyMood(salesData.data?.flatMap(item => item.schedules) || []).color" class="daily-mood">
                  今日感受: {{ calculateDailyMood(salesData.data?.flatMap(item => item.schedules) || []).label }}
                  ({{ calculateDailyMood(salesData.data?.flatMap(item => item.schedules) || []).score }})
                </el-tag>
      </div>
      </div>
            <el-date-picker
              v-model="scheduleDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              class="date-picker"
              @change="() => fetchCensus()"
            />
          </div>
          <div class="chart-container">
            <EchartsPie :options="salesData" height="450px" />
          </div>
        </el-card>
      </el-col>

      <!-- 日程明细折叠区域 -->
      <el-col :md="12" class="detail-col">
        <el-card class="detail-card" shadow="hover">
          <div class="card-header">
            <div class="header-left">
              <h3 class="section-title">
                <el-icon><List /></el-icon>
                日程明细
              </h3>
              <el-tag type="info" class="event-count">
                共 {{ salesData.data?.length || 0 }} 个类别
              </el-tag>
            </div>
          </div>
          <el-collapse v-model="activeNames" accordion class="custom-collapse">
            <el-collapse-item
              v-for="(item, index) in salesData.data"
              :key="item.name"
              :name="index.toString()"
              class="custom-collapse-item"
            >
              <template #title>
                <div class="collapse-title">
                  <div class="title-left">
                    <el-tag :type="getTagType(item.name)" class="category-tag">
                      {{ item.name }}
                    </el-tag>
                    <span class="time-duration">{{ formatMinutesToTime(item.value) }}</span>
                  </div>
                  <div class="title-right">
                    <span v-if="!isMobile" class="schedule-count">{{ item.schedules.length }} 个日程</span>
                    <el-tag :type="calculateDailyMood(item.schedules).color" class="mood-tag">
                      <span v-if="isMobile">{{ calculateDailyMood(item.schedules).label }}</span>
                      <span v-else>{{ calculateDailyMood(item.schedules).label }} ({{ calculateDailyMood(item.schedules).score }})</span>
                    </el-tag>
                  </div>
                </div>
              </template>
              <div class="schedule-content">
                <div v-for="(subItem, subIndex) in item.schedules" :key="subIndex" class="schedule-item">
                  <div class="schedule-item-left">
                    <el-tag type="info" size="small" class="schedule-tag">
                      {{ subItem.scheduleName }}
                    </el-tag>
                    <div class="schedule-info">
                      <span class="schedule-time">
                        <el-icon><Timer /></el-icon>
                        耗时：{{ getDuration(subItem.createTime, subItem.endTime) }}
                      </span>
                      <el-tag size="small" :type="getFeelingType(subItem.feeling)" class="feeling-tag">
                        {{ settleStatusEnum.getLabelByValue(subItem.feeling) }}
                      </el-tag>
                    </div>
                  </div>
                  <div class="schedule-item-right">
                    <span v-if="subItem.motivation" class="schedule-motivation">
                      <el-icon><ChatDotRound /></el-icon>
                      动机：{{ subItem.motivation }}
                    </span>
                  </div>
          </div>
          </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue"; // 修正：添加 computed 导入
import { getCensus, getCensusByFeeling } from "@/api/schedule";
import { PieChart, List, Timer, ChatDotRound, ArrowRight } from '@element-plus/icons-vue'
import { Enum } from "@/utils/enum";


const settleStatusEnum = new Enum()
  .add("UGLY", "丑陋", 1)
  .add("SHIT", "不爽", 2)
  .add("NORMAL", "一般", 3)
  .add("HAPPY", "开心", 4)
  .add("GREAT", "伟大", 5);

// 获取当日时间的函数
const getCurrentDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 初始化 scheduleDate 为当日时间
const scheduleDate = ref(getCurrentDate());
// 初始化 scheduleDate 为当日时间
const feelingDate = ref(getCurrentDate());

// 计算销售额饼图总时间（修正后）
const totalSales = computed(() => {
  // 确保 salesData.value.data 是数组，避免 reduce 报错
  return (salesData.value.data || []).reduce(
    (sum, item) => sum + (item.value || 0),
    0
  );
});

// 获取日程列表
const fetchCensus = async () => {
  try {
    // 封装请求参数
    const data = {
      dayTime: `${scheduleDate.value} 00:00:00`, // 示例参数
      page: 0,
    };
    const resData = await getCensus(data);
    const res = resData.data;
    console.log("API Response:", res);
    // 将后端数据转换为前端结构
    salesData.value = {
      title: "日程统计图",
      data: res.data, // 直接赋值（假设后端返回格式为数组）
    };
  } catch (error) {
    console.error("数据获取失败:", error);
  }
};

// 获取日程列表
const fetchCensusByFeeling = async () => {
  try {
    // 封装请求参数
    const data = {
      dayTime: `${feelingDate.value} 00:00:00`, // 示例参数
      page: 0,
    };
    const resData = await getCensusByFeeling(data);
    const res = resData.data;
    console.log("API Response:", res);
    // 将后端数据转换为前端结构
    userSourceData.value = {
      title: "感受统计图",
      data: res.data, // 直接赋值（假设后端返回格式为数组）
    };
  } catch (error) {
    console.error("数据获取失败:", error);
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchCensus(), fetchCensusByFeeling();
});

const salesData = ref({
  title: "时间统计图",
  data: [
    {
      value: 322,
      name: "工作学习",
      schedules: [
        {
          id: 146,
          scheduleName: "修改标签",
          tagId: 1,
          pastId: 144,
          motivation: null,
          scheduleDes: "",
          feeling: 4,
          createTime: "2025-05-24 01:03:51",
          endTime: "2025-05-24 03:00:56",
          updateTime: "2025-05-23 19:00:56",
          tagName: "工作学习",
        },
      ],
    },
    {
      value: 26,
      name: "琐事",
      schedules: [
        {
          id: 159,
          scheduleName: "琐事",
          tagId: 5,
          pastId: 158,
          motivation: null,
          scheduleDes: "",
          feeling: 3,
          createTime: "2025-05-24 15:16:01",
          endTime: "2025-05-24 15:42:42",
          updateTime: "2025-05-24 07:42:42",
          tagName: "琐事",
        },
      ],
    },
  ],
});

const userSourceData = ref({
  title: "感受统计图",
  data: [
    {
      value: 322,
      name: "工作学习",
      schedules: [
        {
          id: 146,
          scheduleName: "修改标签",
          tagId: 1,
          pastId: 144,
          motivation: null,
          scheduleDes: "",
          feeling: 4,
          createTime: "2025-05-24 01:03:51",
          endTime: "2025-05-24 03:00:56",
          updateTime: "2025-05-23 19:00:56",
          tagName: "工作学习",
        },
      ],
    },
    {
      value: 26,
      name: "琐事",
      schedules: [
        {
          id: 159,
          scheduleName: "琐事",
          tagId: 5,
          pastId: 158,
          motivation: null,
          scheduleDes: "",
          feeling: 3,
          createTime: "2025-05-24 15:16:01",
          endTime: "2025-05-24 15:42:42",
          updateTime: "2025-05-24 07:42:42",
          tagName: "琐事",
        },
      ],
    },
  ],
});

// 新增：分钟转「xx时xx分」的格式化函数
const formatMinutesToTime = (minutes) => {
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}时${remainingMinutes}分`;
};

function getDuration(start, end) {
  if (!start || !end) return "-";
  const startDate = new Date(start);
  const endDate = new Date(end);
  let diff = Math.max(0, endDate - startDate);
  // 处理小于1分钟的情况（1分钟=60000毫秒）
  if (diff < 60000) {
    return "0时1分";
  }
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  return `${hours}时${minutes}分`;
}

// 控制展开的折叠项（空数组表示默认全部折叠）
const activeNames = ref([]);

// 获取标签类型
const getTagType = (name) => {
  const types = {
    '工作学习': 'primary',
    '琐事': 'info',
    '休息': 'success',
    '运动': 'warning',
    '娱乐': 'danger'
  }
  return types[name] || 'info'
}

// 获取感受类型
const getFeelingType = (feeling) => {
  if (feeling >= 4) return 'success'
  if (feeling >= 3) return 'warning'
  return 'danger'
}

// 计算每日心情的函数
const calculateDailyMood = (schedules) => {
  if (!schedules || schedules.length === 0) {
    return {
      score: 0,
      label: '无数据',
      color: '#909399'
    };
  }

  // 计算总时长（分钟）
  const totalDuration = schedules.reduce((total, schedule) => {
    const start = new Date(schedule.createTime);
    const end = new Date(schedule.endTime);
    const duration = Math.max(0, end - start) / (1000 * 60); // 转换为分钟
    return total + duration;
  }, 0);

  // 计算加权平均分
  const weightedScore = schedules.reduce((total, schedule) => {
    const start = new Date(schedule.createTime);
    const end = new Date(schedule.endTime);
    const duration = Math.max(0, end - start) / (1000 * 60); // 转换为分钟
    const weight = duration / totalDuration; // 计算权重
    return total + (schedule.feeling * weight);
  }, 0);

  // 将分数映射到心情描述
  const getMoodInfo = (score) => {
    if (score >= 4.5) return { label: '非常开心', color: '#67C23A' };
    if (score >= 3.5) return { label: '心情不错', color: '#409EFF' };
    if (score >= 2.5) return { label: '一般般', color: '#E6A23C' };
    if (score >= 1.5) return { label: '有点糟', color: '#F56C6C' };
    return { label: '很糟糕', color: '#909399' };
  };

  const moodInfo = getMoodInfo(weightedScore);
  return {
    score: weightedScore.toFixed(1),
    ...moodInfo
  };
};

// 重置查询条件
const reset = () => {
  // ... existing code ...
}

// 添加移动端检测
const isMobile = ref(window.innerWidth <= 768);

// 监听窗口大小变化
window.addEventListener('resize', () => {
  isMobile.value = window.innerWidth <= 768;
});
</script>

<style scoped>
.page-wrapper {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  padding: 24px;
}

@media screen and (max-width: 768px) {
  .page-wrapper {
    padding: 12px;
  }

  .page-container {
    margin: 0;
  }

  .chart-col, .detail-col {
    margin-bottom: 16px;
  }

  .stat-card {
    height: auto;
  }

  .chart-container {
    padding: 0;
  }

  :deep(.el-card__body) {
    padding: 8px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 8px;
    padding-bottom: 8px;
  }

  .header-left {
    width: 100%;
    flex-direction: row;
    align-items: center;
    gap: 8px;
  }

  .section-title {
    font-size: 14px;
    margin: 0;
  }

  .stats-tags {
    flex-direction: row;
    gap: 8px;
  }

  .total-time, .daily-mood {
    font-size: 12px;
    padding: 2px 8px;
  }

  .date-picker {
    width: 100%;
  }
}

.page-container {
  max-width: 1400px;
  margin: 0 auto;
}

.chart-col, .detail-col {
  margin-bottom: 24px;
}

.stat-card, .detail-card {
  height: 100%;
  border-radius: 12px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.stat-card:hover, .detail-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.section-title {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-tags {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.total-time, .event-count {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 16px;
}

.daily-mood {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 16px;
}

.date-picker {
  width: 180px;
}

.chart-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-collapse {
  border: none;
}

.custom-collapse-item {
  margin-bottom: 12px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #fff;
  border: 1px solid #ebeef5;
}

.custom-collapse-item:hover {
  background-color: #f8f9fa;
  border-color: #dcdfe6;
}

.collapse-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
}

.title-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-tag {
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 16px;
}

.time-duration {
  color: #909399;
  font-size: 14px;
}

.title-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.schedule-count {
  font-size: 14px;
  color: #909399;
  /* margin-right: 12px; */
}

.mood-tag {
  font-size: 13px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.collapse-icon {
  transition: transform 0.3s;
  color: #909399;
}

.custom-collapse-item.is-active .collapse-icon {
  transform: rotate(90deg);
}

.schedule-content {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
}

.schedule-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px dashed #ebeef5;
  transition: all 0.3s ease;
}

.schedule-item:hover {
  background-color: #f5f7fa;
}

.schedule-item:last-child {
  border-bottom: none;
}

.schedule-item-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.schedule-tag {
  margin-right: 12px;
}

.schedule-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.schedule-time {
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}

.schedule-item-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.schedule-motivation {
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.feeling-tag {
  min-width: 60px;
  text-align: center;
}

:deep(.el-collapse-item__header) {
  padding: 16px;
  font-size: 15px;
  border-radius: 8px;
  background-color: #fff;
  border: none;
}

:deep(.el-collapse-item__content) {
  padding: 0;
}

:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-icon) {
  vertical-align: middle;
}

/* 励志标语样式 */
.motto-container {
  max-width: 1400px;
  margin: 0 auto 24px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #f0f2f5 0%, #e6e9f0 100%);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

.motto-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.motto-text {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
  letter-spacing: 1px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .motto-container {
    margin: 0 auto 16px;
    padding: 12px 16px;
  }

  .motto-text {
    font-size: 14px;
  }
}
</style>